package ez

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
)

type FileTool struct {
}
type FileUpload struct {
	Name string `json:"name"`
	File string `json:"file"`
}

func (this FileTool) CreateDirForPath(Path string) error {
	Path = path.Clean(Path)
	pathStr := path.Dir(Path)
	pathStr = strings.ReplaceAll(pathStr, "\\", "/")
	pathSlice := strings.Split(pathStr, "/")
	start := ""
	for index, dir := range pathSlice {
		if index == 0 {
			continue
		}
		start = start + "/" + dir
		os.Mkdir(path.Dir(start), 0777)
	}
	return os.Mkdir(path.Dir(Path), 0777)
}

func CleanPath(Path string) string {
	appPath := path.Clean(Path)
	tmp := strings.Split(appPath, string(os.PathSeparator))
	appPath = path.Join(tmp...)
	return appPath
}

func CreateDirForPath(Path string) error {
	Path = path.Clean(Path)
	pathStr := strings.ReplaceAll(Path, `\`, "/")
	pathStr = path.Dir(pathStr)
	pathSlice := strings.Split(pathStr, "/")
	start := ""
	for index, dir := range pathSlice {
		if index == 0 {
			start = dir
			continue
		}
		start = start + "/" + dir
		_, e := os.Stat(start)
		if e == nil {
			continue
		}
		e = os.Mkdir(start, 0777)
		if PrintError(e) {
			return e
		}
	}
	return nil
}

func ReadFile(path string) []byte {
	fileContent, err := os.ReadFile(path)
	if err != nil {
		return fileContent
	}
	return fileContent
}

func (this FileTool) GetExt(Path string) string {
	return path.Ext(Path)
}

func GetCurrentPath() string {
	s, _ := exec.LookPath(os.Args[0])
	i := strings.LastIndex(s, "\\")
	return s[0 : i+1]
}

func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}

func CreateFile(filePath string, content []byte) {
	//数据库配置
	if !FileExist(path.Dir(filePath)) {
		err := CreateDirForPath(filePath)
		if err != nil {
			println("创建路径", err.Error())
		}
	}
	err1 := ioutil.WriteFile(filePath, content, 0777)
	if err1 != nil {
		println("写入文件", err1.Error())
	}
}

type Zipper struct {
	Path   string
	Name   string
	Target string
}

//func ReadExcel(path string) ([][]string, error) {
//	f, err := excelize.OpenFile(path)
//	if err != nil {
//		return nil, err
//	}
//	f.GetActiveSheetIndex()
//	name := f.GetSheetName(f.GetActiveSheetIndex())
//	cols, err := f.Cols(name)
//	if err != nil {
//		return nil, err
//	}
//	var data = make([][]string, 0)
//	for cols.Next() {
//		col, err := cols.Rows()
//		if err != nil {
//			return nil, err
//		}
//		var row = make([]string, 0)
//		for _, rowCell := range col {
//			row = append(row, rowCell)
//		}
//		data = append(data, row)
//	}
//	return data, nil
//}
//
//func CreateZip(fileName string, files ...*Zipper) (string, bool) {
//	root := web.AppConfig.DefaultString("Root", "")
//	dir := GetDate("")
//	zipFilePath := fmt.Sprintf("%s/static/var/tmp/%s/%s.zip", root, dir, fileName)
//	CreateDirForPath(zipFilePath)
//	zipFile, err := os.Create(zipFilePath)
//	if err != nil {
//		return err.Error(), false
//	}
//	zipWriter := zip.NewWriter(zipFile)
//	defer zipWriter.Close()
//	for _, file := range files {
//		fileContent := ReadFile(root + file.Path)
//		if len(fileContent) == 0 {
//			return "文件未找到" + file.Name, false
//		}
//		//ext := path.Ext(file.Path)
//		fwrite, err := zipWriter.Create(file.Name)
//		if err != nil {
//			return "文件创建时发生错误:" + file.Name, false
//		}
//		_, err = fwrite.Write(fileContent)
//		if err != nil {
//			return "文件写入时发生错误:" + file.Name, false
//		}
//	}
//	return zipFilePath[len(root):], true
//}

func Copy(from string, to string) error {
	stat, e := os.Stat(from)
	if e != nil {
		return e
	}
	if !stat.Mode().IsRegular() {
		return errors.New("文件似乎有问题" + from)
	}
	src, e := os.ReadFile(from)
	if e != nil {
		return e
	}
	destFile, e := os.Create(to)
	if e != nil {
		return e
	}
	if destFile != nil {
		defer destFile.Close()
		_, e = destFile.Write(src)
		if e != nil {
			return e
		}
	} else {
		return errors.New("创建文件失败" + to)
	}

	return nil

}

func FindAndOpen(path string) []byte {
	if FileExist(path) {
		return ReadFile(path)
	}
	//向上找10层
	if filepath.IsAbs(path) {
		return nil
	}
	for i := 0; i < 10; i++ {
		path = fmt.Sprintf("./../%s", path[2:])
		content := FindAndOpen(path)
		if content != nil {
			return content
		}
	}

	return nil

}
